package com.junmo.oauth.config.security.authentication;


import com.junmo.oauth.config.security.MyUserDetailService;
import com.junmo.oauth.module.system.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义认证逻辑 : 认证是由 AuthenticationManager 来管理的，
 *  但是真正进行认证的是 AuthenticationManager 中定义的 AuthenticationProvider
 *  Spring Security 默认会使用 DaoAuthenticationProvider
 */
@Component
@Slf4j
@AllArgsConstructor
public class MyAuthenticationProvider  implements AuthenticationProvider {
    private MyUserDetailService myUserDetailsService;
    private RestTemplate restTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
        String userName = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();
        // 查询用户是否存在
        SysUser user = (SysUser) myUserDetailsService.loadUserByUsername(userName);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }

        return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    private void  getToken(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "password");
        map.put("client_id", "clientId");
        map.put("client_secret", "123456");
        map.put("username", "admin");
        map.put("password", "123456");
    }
}
